package com.zzzzzz.account;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresGuest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zzzzzz.core.web.BaseWeb;

@Controller
public class UserWeb extends BaseWeb {
	@Resource
	private UserService userService;
	private static final Logger logger = LoggerFactory.getLogger(UserWeb.class);
	
	@RequiresGuest
	@RequestMapping(value = "/signup", method = RequestMethod.GET)
	public String viewSignUpPage(Model model, @ModelAttribute SignUpForm signUpForm) {
		model.addAttribute("cur", "signup");
		return "account/signup";
	}

	@RequiresGuest
	@RequestMapping(value = "/signup", method = RequestMethod.POST)
	public String processSignUp(Model model, @ModelAttribute SignUpForm signUpForm, BindingResult result, HttpServletRequest request) throws Exception {
		if(result.hasErrors()) {
			result.reject( "message.error.process.request");
			return viewSignUpPage(model, signUpForm);
		}
		try {
			userService.add(signUpForm);

			model.addAttribute("email", signUpForm.getEmail());
			
			return "account/signup_success";
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e; // handle by Spring
		}
	}
}
